﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;

namespace XamlingCore.Infrastructure.Serialisation
{
    public static class Serialise
    {

        public static string SerialiseEntity<TEntity>(TEntity obj)
        {
            return SerialiseEntity<TEntity>(obj, null);
        }

        public static string SerialiseEntity<TEntity>(TEntity obj, IEnumerable<Type> knownTypes)
        {
            DataContractSerializer s;
            
            if (knownTypes != null)
            {
                s = new DataContractSerializer(typeof(TEntity), knownTypes);
            }
            else
            {
                s = new DataContractSerializer(typeof(TEntity));
            }

            using (MemoryStream ms = new MemoryStream())
            {
                s.WriteObject(ms, obj);
                ms.Position = 0;

                using (StreamReader sr = new StreamReader(ms))
                {
                    return sr.ReadToEnd();
                }
            }
        }

        public static TEntity DeSerialiseEntity<TEntity>(string serialisedEntity)
        {
            return DeSerialiseEntity<TEntity>(serialisedEntity, null);
        }
        
        public static TEntity DeSerialiseEntity<TEntity>(string serialisedEntity, IEnumerable<Type> knownTypes)
        {
            DataContractSerializer s;

            if (knownTypes != null)
            {
                s = new DataContractSerializer(typeof(TEntity), knownTypes);
            }
            else
            {
                s = new DataContractSerializer(typeof(TEntity));
            }

            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(serialisedEntity)))
            {
                return (TEntity)s.ReadObject(ms);
            }
        }
    }
}
